#include "yb_form_jcmlxz.h"
#include "ui_yb_form_jcmlxz.h"

#include "pub_var.h"
#include "QPushButton"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QRegExp>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QFile>
#include <QTemporaryFile>
#include <QTextStream>
#include <QElapsedTimer>
#include <QFileDialog>
#include "zip/JlCompress.h"

//#include <QSqlDriver>

QString curBusiness;

Form_yb_jcmlxz::Form_yb_jcmlxz(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_yb_jcmlxz)
{
    ui->setupUi(this);

    ui->cbbPageItems->setVisible(false);
    ui->ckbLocalHospital->setVisible(false);

    //读取配置文件
    QSettings setIni("clin.ini", QSettings::IniFormat);



    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/jcmlxz").toRect();
    this->setGeometry(rct);

    //数据库连接
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);


    //状态显示
    ui->dtStart->setDate(QDate::currentDate());
    ui->de_enddate->setDate(QDate::currentDate());

    dlgDelay = new Pub_pop_delay();
    sqlThread = new sqThread();
    connect( sqlThread, &sqThread::message, this, &Form_yb_jcmlxz::threadMsg);

    //可供使用的交易代码
    qrm->exec("select code,name,ver_mode, down_mode from new_downs where valid_flag = '1' order by code");
    ui->cbbList->clear();
    jydmR.clear();
    QString itm;
    while(qrm->next())
    {
        itm = qrm->value(0).toString().trimmed() ;
        itm.append(" ");
        itm.append(qrm->value(1).toString().trimmed());
        ui->cbbList->addItem(itm);
        itm.append(" ");
        itm.append(qrm->value(2).toString().trimmed());
        itm.append(" ");
        itm.append(qrm->value(3).toString().trimmed());

        jydmR << itm;
    }

    //定时器，控制窗口状态栏显示
    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));
    tm0 = new QTimer(this);
    connect(tm0, SIGNAL(timeout()), this, SLOT(onTime0Out()));

    //定时器，控制延时启动下载
    tm1 = new QTimer(this);
    connect(tm1, SIGNAL(timeout()), this, SLOT(onTime1Out()));

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    //zip动态库存是否存在
    QString zipFile = pub::base_path + "/quazip.dll";
    QFile f;
    if(f.exists(zipFile) ){
        hasZip = true;
    } else {
        hasZip = false;
    }
}

Form_yb_jcmlxz::~Form_yb_jcmlxz()
{
    delete ui;

    delete dlgDelay;
    delete sqlThread;

}

void Form_yb_jcmlxz::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/jcmlxz", QVariant(this->geometry()));
    destroyW("jcmlxz");
}


void Form_yb_jcmlxz::onTimeOut()
{

    //控制状态栏文本闪动显示，当前状态为空则显示状态，状态非空则清空
    if(ui->leStatus->text().isEmpty()){
        ui->leStatus->setText( curStatus );
    }else{
        ui->leStatus->setText("");
    }
    qApp->processEvents();  //刷新显示
}

void Form_yb_jcmlxz::on_pbExit_clicked()
{
    this->close();
}

void Form_yb_jcmlxz::on_pbDownload_clicked()
{

    //测试数据库连接是否有效
    if(!qrm->exec("select curdate() from dual")){
        QMessageBox::information(this,"注意",  "数据库连接异常，操作无法继续！");
        return;
    }

    ui->ckbDownloadStop->setChecked(false);
    if(ui->leBeginPage->text().trimmed().toInt() == 0)
    {
        ui->leBeginPage->setText("1");
    }
    if( ui->ckDelay->isChecked()){

        downloadDelay = ui->leDelay->text().toInt() * 60 ;
        if( downloadDelay <= 0){
            QMessageBox::information(this, "注意", "时间设置无效！");
            return;
        }

        ui->pbExit->setEnabled(false);
        ui->pbQuery->setEnabled(false);
        ui->pbImport->setEnabled(false);
        ui->pbDownload->setEnabled(false);
        ui->pbSimple->setEnabled(false);
        ui->cbbList->setEnabled(false);

        tm1->start(500);
        return;
    }

    endrows = 0;
    nowrows = 0;

    //从列表中提取交易代码
    QString jydm = pub::getStr(ui->cbbList->currentText()," ",1);

    //交易代码关联的下载模式
    foreach(QString i, jydmR){
        if(pub::getStr(i, " ", 1) == jydm){
            ver_mode = pub::getStr(i, " ", 3);
            down_mode = pub::getStr(i, " ", 4);
            break;
       }
    }

    if( jydm == "1901" )
    {
        down1901();
    }
    else if( down_mode == "1")
    {
        if(ui->ckbLocalHospital->isChecked())
        {
            downMode4( jydm );  //只下载本院相关目录
        }else{
            downMode1( jydm );  //下载完整目录
        }

    }
    else if( down_mode == "2")
    {
        downMode2( jydm );
    }
    else if( down_mode == "3" )
    {
        downMode3( jydm );
    }
    else if( down_mode == "4" )
    {
        downMode4( jydm );
    }
    else{
        QMessageBox::warning(NULL,"注意", "下载模式无效！");
        return ;
    }

    return;


    //
    ui->pbExit->setEnabled(false);
    ui->pbQuery->setEnabled(false);
    ui->pbImport->setEnabled(false);
    ui->pbDownload->setEnabled(false);
    ui->pbSimple->setEnabled(false);
    ui->cbbList->setEnabled(false);

    tm->start(390);


    tm->stop();
    ui->leStatus->setText("操作完成");
    ui->pbExit->setEnabled(true);
    ui->pbQuery->setEnabled(true);
    ui->pbImport->setEnabled(true);
    ui->pbDownload->setEnabled(true);
    ui->cbbList->setEnabled(true);

    ui->leBeginPage->clear();
}

void Form_yb_jcmlxz::on_pbQuery_clicked()
{

    sq = "select code,name,ver_mode,last_ver from new_downs where valid_flag = '1' order by code";
    qrm->exec(sq);
    ui->lwResult->clear();
    QString itm;
    while(qrm->next())
    {
        itm = qrm->value("code").toString();
        itm += "\t";
        itm += qrm->value("name").toString();
        itm += "\t";
        itm += qrm->value("last_ver").toString();

        ui->lwResult->addItem(itm);
    }

    ui->leStatus->setText("操作完成");
}

bool Form_yb_jcmlxz::validSave( QString fileName )
{
    //打开指定文本文件，过滤特殊字符 "\", 然后写入新的文件
    QFile sour(fileName);
    QFile dest(fileName + ".txt");

    if(!sour.exists()){
        QMessageBox::warning(NULL,"注意", " 源文件不存在！");
        return false;
    }

    if(dest.exists()){
        if(!dest.remove()){
            QMessageBox::warning(NULL,"注意", " 目标文件存在且无法删除。");
            return false;
        }
    }

    //读取源文件
    sour.open(QFile::ReadOnly);
    QByteArray ar = sour.readAll();
    sour.close();

    //过滤特殊字符
    for(int n = 0; n<ar.length(); n++){
        if(ar[n] == '\\'){
            ar[n] = '/';
        }
        if(ar[n] == '\''){
            ar[n] = ',';
        }
        if(ar[n] == '`'){
            ar[n] = ',';
        }
    }

    //打开目标文件准备写入
    dest.open(QFile::WriteOnly);
    int wrt = dest.write(ar);
    dest.close();
    if( wrt == -1){
        //写入失败
        return false;
    }else{
        //写入成功
        return true;
    }

}

QString Form_yb_jcmlxz::removeSpecialChar(QString s)
{

    s.replace("\\","/");
    s.replace("'","\\'");
//    s.replace("(","\\('");
//    s.replace(")","\\)'");

    return s;
}

void Form_yb_jcmlxz::on_pbSimple_clicked()
{

    //刷新 fin_com_compare 中的医保等级信息
    sq = "select med_list_codg, fixmedins_hilist_name, center_item_grade, list_type "
         " from fin_com_compare ";
    qro->exec(sq);

    qro->last();
    ui->pgbPos->setMaximum(qro->at());
    qro->first();

    QString new_grade,item_code, item_name, old_grade, list_type;

    int count = 0;

    while(true)
    {

        ui->pgbPos->setValue(count++);

        item_code = qro->value(0).toString();
        item_name = qro->value(1).toString();
        old_grade = qro->value(2).toString();
        list_type = qro->value(3).toString();
        sq = "select chrgitm_lv from new_down_1312 where list_type = '";
        sq += list_type + "' and hilist_code = '" + item_code + "' ";
        sq += " and ( enddate is null or enddate > curdate() )";
        qrm->exec(sq);
        qrm->next();
        new_grade = qrm->value(0).toString();

        if(old_grade != new_grade)
        {
            sq = "update fin_com_compare set center_item_grade = '";
            sq += new_grade + "' where  med_list_codg = '" + item_code + "'";
            qrot->exec(sq);
            ui->lwResult->addItem( item_name + " : " + old_grade +" -> " + new_grade );
        }

        if(!qro->next())
        {
            break;
        }

        qApp->processEvents();
    }

    QMessageBox::information(this, "注意", "药品医保等级数据更新已完成！");

    ui->pgbPos->setValue(0);

}

void Form_yb_jcmlxz::onSqlFinished()
{

}

void Form_yb_jcmlxz::onTime0Out()
{

    //控制状态栏文本闪动显示，当前状态为空则显示状态，状态非空则清空
    if(ui->leStatus->text().isEmpty()){
        ui->leStatus->setText( curStatus );
    }else{
        ui->leStatus->setText("");
    }

}

void Form_yb_jcmlxz::onTime1Out()
{

    //控制延时启动下载
    if(!ui->ckDelay->isChecked()){  //中途停止延时
        tm1->stop();

        ui->pbExit->setEnabled(true);
        ui->pbQuery->setEnabled(true);
        ui->pbImport->setEnabled(true);
        ui->pbDownload->setEnabled(true);
        ui->pbSimple->setEnabled(true);

        return;
    }

    if(ui->leDelay->text().isEmpty()){
        downloadDelay -- ;
        ui->leDelay->setText( QString::number(downloadDelay / 60 + 1));
    }else{
        ui->leDelay->setText("");
    }

    if( downloadDelay <= 0 ){
        //停止计时，清除显示，开始下载
        tm1->stop();
        ui->leDelay->setText("");
        ui->ckDelay->setChecked(false);

        ui->pbExit->setEnabled(true);
        ui->pbQuery->setEnabled(true);
        ui->pbImport->setEnabled(true);
        ui->pbDownload->setEnabled(true);
        ui->pbSimple->setEnabled(true);

        on_pbDownload_clicked();
    }
}

void Form_yb_jcmlxz::threadStatusChange(QString s)
{
    qDebug() << "threadStatusChange : " << s;
    curStatus = s;
    if(s == "stop"){    //thread is finished
        tm0->stop();
        //curStatus = "操作完成";
        //tm->stop();
        ui->pbSimple->setEnabled(true);
        ui->pbExit->setEnabled(true);
        ui->pbQuery->setEnabled(true);
        ui->pbImport->setEnabled(true);
        ui->pbDownload->setEnabled(true);
        ui->leStatus->setText(  "操作完成" );
    }

}


void Form_yb_jcmlxz::downMode2(QString busi_code)
{
    //查询最后版本号
    if(ui->cbVersion->isChecked())
    {
        ver_last = ui->leCondition->text().trimmed();
    }else{
        sq = "select ver_mode,down_mode,last_ver from  new_downs where code = '" + busi_code + "'";
        qrm->exec(sq);
        qrm->next();

        ver_last = qrm->value(2).toString();
    }

    if(ver_last.isEmpty())
    {
        QMessageBox::warning(this, "注意", "版本号无效！");
        return ;
    }

    //查询指定交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '" + busi_code + "' order by node_name";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next()){
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        ui->lwResult->addItem( "字段列表无效！。");
        return;
    }

    tm->start(390);

    while(true){

        QJsonObject in, jo_data;    //入参
        jo_data.insert("ver", ver_last);    //最后版本号
        in.insert("data", jo_data);

        QJsonObject jsonRet;    //返回数据
        QString info;       //返回出错信息

        curStatus = "开始进行 "+busi_code+" 交易...";
        qApp->processEvents();

        if( ! pub::call_business(busi_code, in, info, jsonRet, "", false , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            break;
        }
        tm->stop();
        QJsonArray retData = jsonRet.value("output").toObject().value("result").toArray();

        int recCount = retData.size();

        ui->pgbPos->setMaximum(recCount);

        if(recCount == 0){
            ui->lwResult->addItem( busi_code + " 已经是最新版本。");    //返回正常但无数据，表示版本已经是最新。
            ui->leStatus->setText("");
            break;
        }
        else
        {
            ui->lwResult->addItem( busi_code + " 版本 "+ ver_last + " 返回记录 " + QString::number(recCount) + "条");
        }

        int recNow = recCount;

        while(recNow > 0){

            recNow--;
            ui->leStatus->setText("正在导入数据: " + QString::number(recNow) + "/" + QString::number(recCount));
            ui->pgbPos->setValue(recCount - recNow);
            //curStatus = "正在导入数据: " + QString::number(recNow) + "/" + QString::number(recCount);
            qApp->processEvents();

            QString fields, values; //字段列表，返回值列表
            int i = 0;
            bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
            while(true)
            {
                QString retV;
                if(para_type_out[i] == "decimal")
                {
                    retV = QString::number(retData[recNow].toObject().value(para_code_out[i]).toDouble());
                }
                else
                {
                    //过滤字段中对 mysql 有干扰的特殊字符，反斜杠，单引号等。
                    retV = removeSpecialChar(retData[recNow].toObject().value(para_code_out[i]).toString());
                }

                if(!retV.isEmpty() )  //只保存非空字段
                {
                    if(isFirstField)
                    {
                        isFirstField = false;
                        fields += para_code_out[i];
                        values += "'" + retV + "'";
                    }else{
                        fields += ", " + para_code_out[i];
                        values += ", '" + retV + "'";
                    }
                }

                i++;
                if(i >= fieldsCount)    //本行数据是否处理完成
                {
                    break;
                }
            }

            //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
            sq = "replace into new_down_" + busi_code + " (" + fields + ") values (" + values + ")";

            if(!qrm->exec(sq))
            {
                ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");
                if(!ui->ckbIgnoreSql->isChecked())
                {
                    return;
                }
            }
        }
        //保存最新的版本号
        ver_last = retData[0].toObject().value( "ver").toString() ;
        sq = "update new_downs set last_ver = '" + ver_last + "' where code = '" + busi_code + "'";
        qrm->exec(sq);
        if(!ui->cbContinue->isChecked())    // 是否连续导入
        {
            break;
        }
        if(ui->ckbDownloadStop->isChecked())
        {
            break;
        }

    }
    tm->stop();
    ui->pgbPos->setMaximum(100);
    ui->pgbPos->setValue(0);
    ui->leStatus->setText(busi_code+" 交易执行结束。");
}

void Form_yb_jcmlxz::downMode3(QString busi_code)
{
    //查询最后版本号
    ver_last = "";
    if(ui->cbVersion->isChecked())
    {
        ver_last = ui->leCondition->text().trimmed();
        ui->cbVersion->setChecked(false);
    }else{
        sq = "select ver_mode,down_mode,last_ver from  new_downs where code = '" + busi_code + "'";
        qrm->exec(sq);
        qrm->next();

        ver_last = qrm->value(2).toString();
    }

    if(ver_last.isEmpty())
    {
        QMessageBox::warning(this, "注意", "版本号无效！");
        return ;
    }

    tm->start(390);

    while(true){

        ui->lwResult->addItem( "版本号 " + ver_last + " 开始进行下载请求..." );
        ui->lwResult->setCurrentRow(ui->lwResult->count() - 1);

        qApp->processEvents();

        QJsonDocument jsdc;
        QJsonObject in, jo_data;    //入参
        jo_data.insert("ver", ver_last);    //最后版本号
        in.insert("data", jo_data);

        QJsonObject jsonRet;    //返回数据
        QString info;       //返回出错信息

        //ui->leStatus->setText("开始进行 "+busi_code+" 交易...");
        curStatus = "开始进行 "+busi_code+" 交易...";
        qApp->processEvents();

        if( ! pub::call_business(busi_code, in, info, jsonRet, "", true , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            break;

        }

        QString file_qury_no = jsonRet.value("output").toObject().value("file_qury_no").toString();

        in = jsdc.object();
        jo_data = jsdc.object();

        curStatus = "9102 正在下载文本内容。。。";

        jo_data.insert("file_qury_no",file_qury_no);
        jo_data.insert("filename","plc");   //
        jo_data.insert("fixmedins_code", pub::hos_ybbh);   //"0"
        //jo_data.insert("fixmedins_code", ver_last);   //"0"

        in.insert("fsDownloadIn",jo_data);

        if( ! pub::call_business("9102", in, info, jsonRet, "tmp.zip", false , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            break;
        }

        if(hasZip)//zip库可用
        {
            QString baseDir = pub::downloadPath + "/";      //下载路径
            QString dest;                       //目标文件
            //获取压缩包内文件列表
            QStringList contains = JlCompress::getFileList(baseDir+"/tmp.zip");

            if(contains.size() < 1)
            {
                QMessageBox::warning(this, "注意", "下载的压缩包无效！");
                //return ;
                break;
            }

            for (int n = 0; n< contains.length(); n++) {
                //逐个提取压缩包内的文件
                dest = baseDir + contains[n];
                QString ret = JlCompress::extractFile(baseDir+"/tmp.zip", contains[n], dest);

                if(ret.isEmpty()){
                    //提取失败
                    QMessageBox::warning(this, "注意", "压缩文件提取失败！");
                    tm->stop();
                    return ;

                }

                if(!validSave(dest)){
                    QMessageBox::warning(this, "注意", "文本文件转换保存失败！");
                    tm->stop();
                    return ;

                }

                //validSave保存文件时，将转换之后的文件名称附加".txt"
                if(!importText(busi_code, dest+".txt" , ver_mode))
                {
                    tm->stop();
                    return ;
                }
            }
        }
        if(!ui->cbContinue->isChecked())
        {
            // 是否连续导入
            break;
        }

        if(ui->ckbDownloadStop->isChecked())
        {
            // 是否需要停止
            break;
        }
    }

    tm->stop();

    ui->leStatus->setText(busi_code+" 交易执行结束。");
}

bool Form_yb_jcmlxz::importText(QString busiCode, QString fileName, QString verMode)
{

    if (fileName.isEmpty() || busiCode.isEmpty() || verMode.isEmpty())
    {
        QMessageBox::warning(this, "注意", "importText 收到无效参数！");
        return false;
    }

    QFile textFile(fileName);

    if(!textFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(this, "注意", "无法打开指定名称的文件！");
        return false;
    }

    //查询指定交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '" + busiCode + "' order by node_name";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next())
    {
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        QMessageBox::warning(this, "注意", "字段列表无效！");
        return false;
    }

    QTextStream txtstrm(&textFile);
    if(ui->rbUtf8->isChecked())    //字符集选择
    {
        txtstrm.setCodec("UTF-8");
    }

    QString textLine;
    QStringList lineData;

    int lineCount = 0;
    int charsCount = 0;
    ui->pgbPos->setMaximum(textFile.size());

    textLine = txtstrm.readLine();   //读取一行
    lineData = textLine.split("\t");
    int idx = para_code_out.indexOf(verMode);
    if( idx < 0 )
    {
        QMessageBox::warning(this, "注意", " 字段列表中找不到预设的版本模式！ ");
        return false;
    }
    ver_last = lineData[idx];

    txtstrm.seek(0);    //文件指针归零
    int pieces = 0; //文件片断
    if(ui->rbFast->isChecked())
    {   //快速导入
        while(true){
            pieces ++ ;

            QTemporaryFile tmpfl;
            tmpfl.open();
            QString tmpLine;

            for(int lines = 0; lines < 999; lines ++)
            {
                tmpLine = txtstrm.readLine();   //读取一行
                charsCount += textLine.size();
                ui->pgbPos->setValue(charsCount);
                tmpfl.write(tmpLine.toUtf8().data());
                if(tmpLine.isEmpty())//到达文件末尾
                {
                    break;
                }

                //tmpfl.write(lineEnd.toLatin1().data());
                tmpfl.write("\r\n");
            }
            tmpfl.close();

            //如果文件内容为空，SQL语句执行无结果也不报错，所以这里不对文件是否为空进行判断

            ui->leStatus->setText( "正在导入第 " + QString::number( pieces ) + " 个文件片断......");
            qApp->processEvents();  //刷新显示

            //临时生成的文本文件格式为 utf8
            qrm->exec("set names utf8");
            sq = " load data local infile '" + tmpfl.fileName() + "' ";
            sq += "replace into table new_down_" + busiCode;
            if(!qrm->exec(sq)){
                qDebug()<<"sql error: " << qrm->lastError().text()<< "  sql : " << sq;
                qDebug()<< tmpfl.fileName() << " 导入数据失败。 " ;
                //保存导入失败的文件片段
                QFile::copy(tmpfl.fileName(),  fileName + QString::number(pieces));
                ui->lwResult->addItem(" 导入数据失败: " + qrm->lastError().text());
                if(!ui->ckbIgnoreSql->isChecked())
                {
                    return false;
                }

            }

            if(tmpLine.isEmpty()){  //最后一次取到的是空行，终止导入
                break;
            }
        }
    }
    else
    {
        //医保返回数据格式变化快速导入无法进行，可逐行导入
        while(true)
        {
            lineCount ++ ;

            textLine = txtstrm.readLine();   //读取一行
            charsCount += textLine.toUtf8().size();
            ui->pgbPos->setValue(charsCount);

            if(textLine.isEmpty()){  //到达文件末尾
                break;
            }

            lineData = textLine.split("\t");

            ui->leStatus->setText( "正在导入第 " + QString::number( lineCount ) + " 行......");
            qApp->processEvents();  //刷新显示

            QString fields, values; //字段列表，返回值列表
            int columns = 0;
            bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
            while(true)
            {
                QString retV = lineData[columns];

                if(!retV.isEmpty())  //只保存非空字段
                {
                    if(isFirstField)
                    {
                        isFirstField = false;
                        fields += para_code_out[columns];
                        values += "'" + retV + "'";
                    }else{
                        fields += ", " + para_code_out[columns];
                        values += ", '" + retV + "'";
                    }
                }

                columns++;
                if(columns >= fieldsCount)    //本行数据是否处理完成
                {
                    break;
                }
            }

            //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
            sq = "replace into new_down_" + busiCode + " (" + fields + ") values (" + values + ")";

            if(!qrm->exec(sq)){
                ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");
                if(!ui->ckbIgnoreSql->isChecked())
                {
                    return false;
                }
            }
        }
    }
    //保存最新的版本号
    sq = "update new_downs set last_ver = '" + ver_last + "' where code = '" + busiCode + "'";
    qrm->exec(sq);
    sq = " insert into com_download_version (version, jydm, datetime) "
         " values('" + ver_last + "','" + busiCode + "',now())";
    qrm->exec(sq);
    ui->pgbPos->setValue(0);
    ui->leStatus->setText( "文本导入结束。");
    qApp->processEvents();  //刷新显示

    return true;
}

void Form_yb_jcmlxz::down1901()
{

    //查询指定交易出参数据结构
    QJsonObject in, jo_data;    //入参

    jo_data.insert("type", "");
    jo_data.insert("admdvs", pub::hos_insuplc);
    jo_data.insert("date", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    jo_data.insert("vali_flag", "1");

    in.insert("data", jo_data);

    QJsonObject jsonRet;    //返回数据
    QString info;       //返回出错信息

    //ui->leStatus->setText("开始进行 "+busi_code+" 交易...");
    curStatus = "开始进行 1901 交易...";
    qApp->processEvents();
    tm->start(390);
    if( ! pub::call_business("1901", in, info, jsonRet, "", false , manager, request))
    {
        QMessageBox::warning(this, "注意", info);
        tm->stop();
        return;
    }
    tm->stop();
    qrm->exec("delete from com_dict_new");
    QJsonArray retData = jsonRet.value("output").toObject().value("list").toArray();;

    int recCount = retData.size();
    int recNow = recCount;
    ui->pgbPos->setMaximum(recCount);

    while(recNow > 0)
    {

        recNow--;
        ui->leStatus->setText("正在导入数据: " + QString::number(recNow) + "/" + QString::number(recCount));
        ui->pgbPos->setValue(recCount - recNow);
        qApp->processEvents();

        QJsonObject ob = retData[recNow].toObject();

        sq = "insert into com_dict_new"
             " (dic_type,dic_label,dic_value,parent_value,sort,"
             "vali_flag,version)"
             "values ('"
                + ob.value("type").toString().replace("'", "/")
                + "','" + ob.value("label").toString().replace("'", "/")
                + "','" + ob.value("value").toString().replace("'", "/")
                + "','" + ob.value("parent_value").toString().replace("'", "/")
                + "'," + QString::number(ob.value("sort").toDouble())
                + ",'" + ob.value("vali_flag").toString()
                + "'," + QString::number(ob.value("version").toDouble())
                + ")";

        if(!qrm->exec(sq))
        {
            qDebug()<<"sql error: " << qrm->lastError().text();
            qDebug()<< "sql : " << sq;
            qDebug()<< "com_dict_new insert error. " ;
        }
    }

    tm->stop();
    ui->leStatus->setText(" 1901交易执行结束。");
}

void Form_yb_jcmlxz::downMode1(QString busi_code)
{
    //查询最后版本号
    ver_last = "";

    if(ui->rbSpecial->isChecked())
    {
        ver_last = ui->dtStart->date().toString("yyyy-MM-dd");
    }else{
        sq = "select ver_mode,down_mode,last_ver from  new_downs where code = '" + busi_code + "'";
        qrm->exec(sq);
        qrm->next();
        ver_last = qrm->value(2).toString();
    }

    if(ver_last.isEmpty())
    {
        QMessageBox::warning(this, "注意", "版本号无效！");
        return ;
    }

    //查询交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '" + busi_code + "' order by node_name";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next()){
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        ui->lwResult->addItem( "字段列表无效！。");
        return;
    }

    QJsonObject inpu,in;

    int pages = ui->leBeginPage->text().toInt();  //页数
    int allPages = 0;
    ui->leStatus->setText("准备开始导入数据。。。" );
    curStatus = "准备开始导入数据。。。";
    qApp->processEvents();
    tm->start(390);

    while(true)
    {
        if(ui->ckbDownloadStop->isChecked())
        {
            break;
        }
        inpu.insert("fixmedins_code", pub::hos_ybbh);
        inpu.insert("insu_admdvs",pub::hos_insuplc);
        inpu.insert("updt_time", ver_last);   //更新时间
        inpu.insert("page_num", pages);    //当前页数
        inpu.insert("page_size", ui->cbbPageItems->currentText());   //本页数据量

        in.insert("data",inpu);

        QJsonObject jsonRet;    //返回数据
        QString info;       //返回出错信息

        curStatus = "开始进行 "+busi_code+" 交易...";
        qApp->processEvents();

        if( ! pub::call_business(busi_code, in, info, jsonRet, "", false , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            break;
        }

        allPages = jsonRet.value("output").toObject().value("pages").toInt();
        ui->leStatus->setText("正在导入数据第 " + QString::number(pages) + " 页 / 共 " + QString::number(allPages) + " 页。" );
        curStatus = "正在导入数据第 " + QString::number(pages) + " 页 / 共 " + QString::number(allPages) + " 页。";

        int recCount = jsonRet.value("output").toObject().value("size").toInt();
        if(recCount == 0){
            lastPage = true;
            QMessageBox::warning(NULL,"注意", busi_code + " 返回数据集为空！ ");
            tm->stop();
            return ;
        }
        ui->pgbPos->setMaximum(recCount);

        QJsonArray retData = jsonRet.value("output").toObject().value("data").toArray();
        //qDebug()<<jsonRet;
        int recNow = recCount;

        while(recNow > 0){
            QJsonObject ob = retData[recCount].toObject();
            recNow--;

            ui->pgbPos->setValue(recCount - recNow);

            qApp->processEvents();

            QString fields, values; //字段列表，返回值列表
            int i = 0;
            bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
            while(true)
            {
                QString retV;
                if(para_type_out[i] == "decimal")
                {
                    retV = QString::number(retData[recNow].toObject().value(para_code_out[i]).toDouble());
                }
                else
                {
                    //过滤字段中对 mysql 有干扰的特殊字符，反斜杠，单引号等。
                    retV = removeSpecialChar(retData[recNow].toObject().value(para_code_out[i]).toString());
                }
                if(!retV.isEmpty())  //只保存非空字段
                {
                    if(isFirstField)
                    {
                        isFirstField = false;
                        fields += para_code_out[i];
                        values += "'" + retV + "'";
                    }else{
                        fields += ", " + para_code_out[i];
                        values += ", '" + retV + "'";
                    }
                }

                i++;
                if(i >= fieldsCount)    //本行数据是否处理完成
                {
                    break;
                }
            }

            //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
            sq = "replace into new_down_" + busi_code + " (" + fields + ") values (" + values + ")";

            if(!qrm->exec(sq)){
                ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");

                if(!ui->ckbIgnoreSql->isChecked())
                {
                    tm->stop();
                    return;
                }
            }
        }

        if(jsonRet.value("output").toObject().value("lastPage").toBool())
        {
            //最后一页
            break;
        }
        pages++;
        ui->leBeginPage->setText(QString::number(pages));

    }

    //保存最新的版本号
    ver_last = QDate::currentDate().toString("yyyy-MM-dd");
    sq = "update new_downs set last_ver = '" + ver_last + "' where code = '" + busi_code + "'";
    qrm->exec(sq);
    sq = " insert into com_download_version (version, jydm, datetime) "
         " values('" + ver_last + "','" + busi_code + "',now())";
    qrm->exec(sq);
    ui->pgbPos->setValue(0);
    tm->stop();
    ui->leStatus->setText( "导入结束。");
    qApp->processEvents();  //刷新显示

}
void Form_yb_jcmlxz::downMode4(QString busi_code)
{
    //查询三年以内的数据
    ver_last = ui->dtStart->date().addYears( - 3).toString("yyyy-MM-dd");

    //查询交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '" + busi_code + "' order by node_name";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next()){
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        ui->lwResult->addItem( "字段列表无效！。");
        return;
    }

    QJsonObject inpu,in;

    int recCount = 0;  //需要操作的记录数

    ui->leStatus->setText("准备开始导入数据。。。" );
    curStatus = "准备开始导入数据。。。";
    qApp->processEvents();

    sq = "select count(*) from new_down_1317 ";
    qrmt->exec(sq);
    qrmt->next();

    int maxCount = qrmt->value(0).toInt();
    if(maxCount == 0)
    {
        QMessageBox::information(this, "注意", "1317表空白，请先下载1317数据！");
        return;
    }
    ui->pgbPos->setMaximum(maxCount);

    sq = "select med_list_codg, fixmedins_hilist_name from fin_com_compare ";
    qro->exec(sq);
    //sq = "select med_list_codg, medins_list_name from new_down_1317";
    //qrmt->exec(sq);

    while(qro->next())
    {
        recCount++;
        inpu.insert("hilist_code", qro->value(0).toString());
        inpu.insert("vali_flag", "1");
        inpu.insert("insu_admdvs",pub::hos_insuplc);
        inpu.insert("updt_time", ver_last);   //更新时间
        inpu.insert("page_num", 1);    //当前页数
        inpu.insert("page_size", 1000);   //本页数据量

        in.insert("data",inpu);

        QJsonObject jsonRet;    //返回数据
        QString info;       //返回出错信息

        //ui->leStatus->setText( "开始进行 "+busi_code+" 交易...");
        //qApp->processEvents();

        if( ! pub::call_business(busi_code, in, info, jsonRet, "", false , manager, request))
        {
            QMessageBox::warning(this, "注意", info);
            tm->stop();
            break;
        }

        ui->pgbPos->setValue(recCount);

        ui->leStatus->setText("正在导入数据 " + QString::number(recCount) + "/" + QString::number(maxCount)+" ：" +qro->value(1).toString());

        qApp->processEvents();

        int recNow = jsonRet.value("output").toObject().value("size").toInt();
        if( recNow == 0)
        {
            continue ;
        }

        QJsonArray retData = jsonRet.value("output").toObject().value("data").toArray();

        while(recNow > 0){

            if(ui->ckbDownloadStop->isChecked())
            {
                break;
            }

            QJsonObject ob = retData[recCount].toObject();
            recNow--;

            QString fields, values; //字段列表，返回值列表
            int i = 0;
            bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
            while(true)
            {
                QString retV;
                if(para_type_out[i] == "decimal")
                {
                    retV = QString::number(retData[recNow].toObject().value(para_code_out[i]).toDouble());
                }
                else
                {
                    //过滤字段中对 mysql 有干扰的特殊字符，反斜杠，单引号等。
                    retV = removeSpecialChar(retData[recNow].toObject().value(para_code_out[i]).toString());
                }
                if(!retV.isEmpty() )  //只保存非空字段
                {
                    if(isFirstField)
                    {
                        isFirstField = false;
                        fields += para_code_out[i];
                        values += "'" + retV + "'";
                    }else{
                        fields += ", " + para_code_out[i];
                        values += ", '" + retV + "'";
                    }
                }

                i++;
                if(i >= fieldsCount)    //本行数据是否处理完成
                {
                    break;
                }
            }

            //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
            sq = "replace into new_down_" + busi_code + " (" + fields + ") values (" + values + ")";

            if(!qrm->exec(sq))
            {
                ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");
                if(!ui->ckbIgnoreSql->isChecked())
                {
                    return;
                }
            }
        }

    }

    //保存最新的版本号
    ver_last = QDate::currentDate().toString("yyyy-MM-dd");
    sq = "update new_downs set last_ver = '" + ver_last + "' where code = '" + busi_code + "'";
    qrm->exec(sq);
    sq = " insert into com_download_version (version, jydm, datetime) "
         " values('" + ver_last + "','" + busi_code + "',now())";
    qrm->exec(sq);
    ui->pgbPos->setValue(0);
    tm->stop();
    ui->leStatus->setText( "导入结束。");
    qApp->processEvents();  //刷新显示

}

void Form_yb_jcmlxz::on_cbbList_currentIndexChanged(int index)
{
    ui->leBeginPage->clear();
}

void Form_yb_jcmlxz::on_pb_update_icpc_clicked()
{

    QString icpc_code, icpc_name, item_type , new_code;

    sq = " SELECT * FROM com_dict_icpc where icpc_code <> '0' and valid_flag = '1' ";
    qrm->exec(sq);
    qrm->last();
    ui->pgbPos->setMaximum(qrm->at());
    qrm->first();
    int count = 0;

    QStringList sqls; //需要统一执行的语句

    while(true)
    {
        ui->pgbPos->setValue(count++);

        icpc_code = qrm->value("icpc_code").toString();
        icpc_name = qrm->value("icpc_name").toString();
        item_type = qrm->value("type").toString();

        if(item_type == "0" || item_type == "2")
        {
            //就诊原因与诊断
            sq = " select six_code,six_name "
                 " from new_down_1361 where six_name = '%1' "
                 " union "
                 " select six_code,six_name "
                 " from new_down_1361 where icd10_asoc_name = '%1'";

            sq = sq.arg(icpc_name);
            qDebug()<<"在1361中提取新编码 : "<<sq;
            qrmt->exec(sq);

            if(qrmt->next())
            {
                new_code = qrmt->value("six_code").toString();

                if(icpc_code != new_code)
                {
                    sq = "update com_dict_icpc set icpc_code = '%1' "
                         " where icpc_name = '%2' and type in ('0','2')";
                    sq = sq.arg(new_code).arg(icpc_name);

                    sqls << sq;
                    //qrmt->exec(sq);
                    ui->lwResult->addItem( icpc_name + " : " + icpc_code +" -> " + new_code );
                    qApp->processEvents();
                }
            }
            else
            {
                sq = "update com_dict_icpc set valid_flag = '0' "
                     " where icpc_name = '%1' and type in ('0','2')";
                sq = sq.arg(icpc_name);
                //qrmt->exec(sq);
                sqls << sq;
                qDebug()<<"变更icpc编码 : "<<sq;
                ui->lwResult->addItem( icpc_name + " : 目录已经撤销。");
                qApp->processEvents();

            }
        }
        else if(item_type == "1" || item_type == "3")
        {
            //治疗
            sq = "select icpc_code,chrgitm_name from new_down_1362 "
                 " where chrgitm_name = '%1'";

            sq = sq.arg(icpc_name);
            qDebug()<<"在1362中提取新编码 : "<<sq;
            qrmt->exec(sq);

            if(qrmt->next())
            {
                new_code = qrmt->value("icpc_code").toString();

                if(icpc_code != new_code)
                {
                    sq = "update com_dict_icpc set icpc_code = '%1' "
                         " where icpc_name = '%2' and type in ('1','3')";
                    sq = sq.arg(new_code).arg(icpc_name);
                    //qrmt->exec(sq);
                    sqls << sq;

                    qDebug()<<"变更icpc编码 : "<<sq;

                    ui->lwResult->addItem( icpc_name + " : " + icpc_code +" -> " + new_code );
                    qApp->processEvents();
                }
            }
            else
            {
                sq = "update com_dict_icpc set valid_flag = '0' "
                     " where icpc_name = '%1' and type in ('1','3')";
                sq = sq.arg(icpc_name);
                qDebug()<<"变更icpc编码 : "<<sq;

                sqls << sq;
                ui->lwResult->addItem( icpc_name + " : 目录已经撤销。");
                qApp->processEvents();
            }

        }

        if(!qrm->next())
        {
            break;
        }
    }

    //此时统一执行 sql，避免干扰 qrm 主循环

    qDebug()<<"sqls will execute : "<<sqls;
    foreach(QString s, sqls)
    {
        qDebug()<<s;
        qrmt->exec(s);
    }

    QMessageBox::information(this, "注意", "ICPC数据更新已完成！");

    ui->pgbPos->setValue(0);
}

void Form_yb_jcmlxz::on_pb_check_price_clicked()
{
    qDebug()<<"\non_pb_check_price_clicked，开始核查价表信息。。。\n";

    qDebug()<<"提取本地非0，存在医保码的药品目录\n";
    sq = "select distinct "
         " trade_name, drug_code,med_list_codg,"
         " retail_price, pack_qty "
         " from PHA_COM_STORAGE "
         " where STORE_SUM > 0 and MED_LIST_CODG is not null";
    qDebug()<<sq<<"\n";

    qro->exec(sq);

    ui->lwResult->addItem( "药品价格核对：\n" );

    QString item_name, insu_code, drug_code;
    double local_price;
    int pack_qty;

    while(qro->next())
    {
        item_name = qro->value("trade_name").toString();
        insu_code = qro->value("med_list_codg").toString();
        drug_code = qro->value("drug_code").toString();
        pack_qty = qro->value("pack_qty").toDouble();
        local_price = qro->value("retail_price").toDouble() / pack_qty;


        qDebug()<<"提取医保限价目录";
        sq = " select hilist_pric_uplmt_amt from new_down_1318"
             " where hilist_code = '%1' "
             " and begndate <= curdate() "
             " and (enddate > curdate() or enddate is null)"
             " and hilist_lmtpric_type in ('0','9919','902')"//不分级，一级，一般药品限
             " order by begndate desc ";
        sq = sq.arg(insu_code);
        qDebug()<<sq<<"\n";

        qrm->exec(sq);
        if(qrm->next())
        {
            double insu_price = qrm->value(0).toDouble();

            double diff= insu_price - local_price;

            if(pub::isAlmostEqual( diff, 0))
            {
                //价格一致
            }
            else
            {

                qDebug()<<"dfa;sldkjo;sad"<<sq;;

                //insu_price != price
                ui->lwResult->addItem( item_name
                                       + "/"
                                       + drug_code
                                       + "/"
                                       + insu_code
                                       + " : "
                                       + " 本地价格："
                                       + QString::number(local_price * pack_qty)
                                       //+ "/"
                                       //+ QString::number(local_price)
                                       + " , 医保限价："
                                       + QString::number(insu_price * pack_qty)
                                       //+ "/"
                                       //+ QString::number(insu_price)
                                       );
            }
        }
    }

    qDebug()<<"提取本地有效非药品项目价格目录\n";
    sq = "select distinct "
         " com.med_list_codg, un.item_code, un.item_name, un.unit_price"
         " from fin_com_compare com "
         " left join fin_com_undruginfo un "
         "      on un.item_code = com.fixmedins_hilist_id "
         " where un.valid_state = '1' ";

    qDebug()<<sq<<"\n";

    qro->exec(sq);

    ui->lwResult->addItem( "\n非药品价格核对：\n" );

    while(qro->next())
    {
        item_name = qro->value("item_name").toString();
        insu_code = qro->value("med_list_codg").toString();
        drug_code = qro->value("item_code").toString();
        //pack_qty = qro->value("pack_qty").toDouble();
        local_price = qro->value("unit_price").toDouble();


        qDebug()<<"提取医保限价目录";
        sq = " select hilist_pric_uplmt_amt from new_down_1318"
             " where hilist_code = '%1' "
             " and  begndate <= curdate() "
             " and (enddate > curdate() or enddate is null)"
             " and hilist_lmtpric_type in ('0','9919','902')" //不分级，一级，一般药品限
             " order by begndate desc ";
        sq = sq.arg(insu_code);
        qDebug()<<sq<<"\n";

        qrm->exec(sq);
        if(qrm->next())
        {
            double insu_price = qrm->value(0).toDouble();
            if(pub::isAlmostEqual(insu_price, local_price))
            {
                //价格一致
            }
            else //if (insu_price > price)
            {
                //医保价高于本地
                ui->lwResult->addItem( item_name
                                       + "/"
                                       + drug_code
                                       + "/"
                                       + insu_code
                                       + " : "
                                       + " 本地价格："
                                       + QString::number(local_price)
                                       + " , 医保限价："
                                       + QString::number(insu_price));

            }
        }
    }


    ui->lwResult->addItem( "\n价格核对完成。\n" );

    qDebug()<<"on_pb_check_price_clicked 核查价表信息完成。\n";
}

void Form_yb_jcmlxz::threadMsg(QString s)
{
    if(s == "finish"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
    }
    else if(s.left(3) == "msg")
    {
        dlgDelay->setText(sqlMsg[pub::getStr(s, "^", 2).toInt()]);
    }
    else if(s.left(8) == "rollback")
    {
        dlgDelay->setText("线程 SQL 发生错误，正在回滚。。。");
    }
    else if(s.left(3) == "err"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        qDebug()<<" SQL thread " +s;
        QMessageBox::warning(this, "注意", "线程中的sql执行发生错误！\n" + s);
    }
    else
    {
        qDebug()<<" SQL thread return invalid message : " +s;
    }
}

bool Form_yb_jcmlxz::status_check_invalid_data()
{
    QDate dt_selected = ui->de_enddate->date();
    QDate dt_cur = QDate::currentDate();

    if(dt_selected >= dt_cur)
    {
        QMessageBox::information(this,"注意",  "不允许处理未过期数据！");
        return false;
    }

    if( !ui->ckb_1312->isChecked()
            && !ui->ckb_1318->isChecked())  //&&  !ui->ckb_1319->isChecked()
    {
        QMessageBox::information(this,"注意",  "未选择数据！");
        return false;
    }

    return true;
}

void Form_yb_jcmlxz::on_pbImport_clicked()
{

    if(!status_check_invalid_data())
    {
        return;
    }

    QMessageBox::StandardButton bt;
    bt = QMessageBox::question(this, "注意", "即将删除过期数据，此操作不可逆！确认继续？");
    if(bt != QMessageBox::Yes)
    {
        return ;
    }

    QStringList sqls;   //准备向线程传送的sql集合
    sqlMsg.clear();

    if(ui->ckb_1312->isChecked())
    {
        sqlMsg << "删除 new_down_1312 过期数据。。。";
        sq = "mdelete from new_down_1312 "
             " where enddate < str_to_date('"
                + ui->de_enddate->date().toString("yyyy-MM-dd")
                + "','%Y-%m-%d')";
        sqls << sq;

        sqlMsg << "优化 new_down_1312 数据存储。。。";
        sq = "moptimize table new_down_1312";
        sqls << sq;

    }

    if(ui->ckb_1318->isChecked())
    {
        sqlMsg << "删除 new_down_1318 过期数据。。。";
        sq = "mdelete from new_down_1318 "
             " where enddate < str_to_date('"
                + ui->de_enddate->date().toString("yyyy-MM-dd")
                + "','%Y-%m-%d')";
        sqls << sq;

        sqlMsg << "优化 new_down_1318 数据存储。。。";
        sq = "moptimize table new_down_1318";
        sqls << sq;

    }

//    if(ui->ckb_1319->isChecked())
//    {
//        sqlMsg << "删除 new_down_1319 过期数据。。。";
//        sq = "mdelete from new_down_1319 "
//             " where enddate < str_to_date('"
//                + ui->de_enddate->date().toString("yyyy-MM-dd")
//                + "','%Y-%m-%d')";
//        sqls << sq;

//        sqlMsg << "优化 new_down_1319 数据存储。。。";
//        sq = "moptimize table new_down_1319";
//        sqls << sq;

//    }

    sqlMsg << "发生错误，正在回滚数据。。。";

    qDebug()<<"sqls will send to thread process : "<<sqls;
    sqlThread->setSqls(sqls);

    sqlThread->start();
    dlgDelay->setNeedClose(false);
    dlgDelay->exec();

    if(sqlThread->getLastError())
    {
        //sql语句执行遇到错误
        return;
    }

    ui->leStatus->setText("数据整理结束！");
}

void Form_yb_jcmlxz::on_pb_invalid_check_clicked()
{
    if(!status_check_invalid_data())
    {
        return;
    }

    ui->leStatus->setText("正在计算。。。");

    sq = "SELECT table_name, table_rows "
         " FROM information_schema.tables "
         " WHERE table_schema = 'clinic' "
         " and table_name in('new_down_1312','new_down_1318') " //,'new_down_1319'
         " order by table_name";

    qrm->exec(sq);
    qrm->next();
    QString rows_1312 = qrm->value(1).toString();

    qrm->next();
    QString rows_1318 = qrm->value(1).toString();

    //qrm->next();
    //QString rows_1319 = qrm->value(1).toString();

    if(ui->ckb_1312->isChecked())
    {
        ui->lwResult->addItem("开始计算 new_down_1312 数据 ... " );
        qApp->processEvents();

        sq = " select count(*) from new_down_1312 "
             " where enddate < str_to_date('"
                + ui->de_enddate->date().toString("yyyy-MM-dd")
                + "','%Y-%m-%d')";
        qrm->exec(sq);
        qDebug()<<"计算 1312 : " << sq;
        qrm->next();

        ui->lwResult->addItem("new_down_1312 当前数据总数 "
                              + rows_1312
                              + " ，失效数据 "
                              + qrm->value(0).toString());
        qApp->processEvents();
    }

    if(ui->ckb_1318->isChecked())
    {
        ui->lwResult->addItem("开始计算 new_down_1318 数据 ... " );
        qApp->processEvents();
        sq = " select count(*) from new_down_1318 "
             " where enddate < str_to_date('"
                + ui->de_enddate->date().toString("yyyy-MM-dd")
                + "','%Y-%m-%d')";
        qrm->exec(sq);
        qDebug()<<"计算 1318 : " << sq;
        qrm->next();

        ui->lwResult->addItem("new_down_1318 当前数据总数 "
                              + rows_1318
                              + " ，失效数据 "
                              + qrm->value(0).toString());
        qApp->processEvents();

    }

//    if(ui->ckb_1319->isChecked())
//    {
//        ui->lwResult->addItem("开始计算 new_down_1319 数据 ... " );
//        qApp->processEvents();

//        sq = " select count(*) from new_down_1319 "
//             " where enddate < str_to_date('"
//                + ui->de_enddate->date().toString("yyyy-MM-dd")
//                + "','%Y-%m-%d')";
//        qrm->exec(sq);
//        qDebug()<<"计算 1319 : " << sq;
//        qrm->next();

//        ui->lwResult->addItem("new_down_1319 当前数据总数 "
//                              + rows_1319
//                              + " ，失效数据 "
//                              + qrm->value(0).toString());

//    }
    ui->leStatus->setText("计算结束！");



}
